#! /usr/bin/python
# -*- coding: cp1250 -*-

import re, string, sys, glob, os, time, shutil
import pepe.p_utils.txt2pg as ppt
import pepe.p_sql.pg as pg
import pepe.p_oslevel.basic as posb

#print posb.wai()

def listTables():
    ''' '''
    res = []
    q = """select * from pg_tables where schemaname='public'"""
    for r in pg.Pg(q):
        res.append(r[1])
    return res

def dropTable(t):
    ''' '''
    #pg.Pg("""drop table %s""" % (t,))
    try:
        pg.Pg("drop table %s" % (t,))
        return 1
    except:
        return 0

def loadData(fMask='', cDelimiter=''):
    ''' '''
    files = glob.glob(fMask)
    for f in files:
        # table name
        t = f[:-4]
        # drop table if exists
        if t in listTables(): dropTable(t)

        p = ppt.TxtLoad(  inputFile=f
                        , colDelimiter=cDelimiter
                        , hasHeader=0
                        )
        p.dropTableBefore = 0
        #p.pgClientEncoding = 'UTF8'
        #p.pgClientEncoding = 'cp1250'
        p.createTable()
        p.loadData()

def jkpg(fMask='', cDelimiter=''):
    ''' '''
    files = glob.glob(fMask)
    for f in files:
        # table name
        t = f[:-4]
        # drop table if exists
        if t in listTables(): dropTable(t)

        p = ppt.TxtLoad(  inputFile=f
                        , colDelimiter=cDelimiter
                        , hasHeader=0
                        )
        p.dropTableBefore = 0
        #p.pgClientEncoding = 'UTF8'
        #p.pgClientEncoding = 'cp1250'
        p.createTable()
        p.loadData()

    #if 'temp_jpkg' in listTables(): dropTable('temp_jpkg')
    
    q = """   COPY 
                (
                select t1.*, t2.* from %s as t1
                full join %s as t2 on t1.c001 = t2.c001
                order by t1.c001
                )
                TO '%s#jkpg.txt' with DELIMITER '^' NULL ''
                """ % (files[0][:-4], files[1][:-4], posb.wai())
    #print q
    pg.Pg(q)
    for f in files:
        dropTable(f[:-4])

if __name__ == '__main__':
    ''' '''
    #jkpg(fMask='*.dat', cDelimiter='\t')
    print dropTable('AMOtb0409')
    print dropTable('AMOtb0412')
    print listTables()
    #print dropTable('aaa3')